package com.future.mayi.activity;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.future.baselib.entity.DefaultResponse;
import com.future.baselib.utils.ApiCst;
import com.future.baselib.utils.HttpRequest;
import com.future.mayi.R;
import com.future.mayi.app.App;
import com.future.mayi.model.AddressModel;
import com.future.mayi.model.NewGoodsOrderModel;
import com.future.mayi.qsale.model.CartListModel;
import com.future.mayi.response.AddressResponse;
import com.future.mayi.utils.HCUtils;
import com.future.mayi.utils.PriceUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.Serializable;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class NewGoodsOrderActivity extends BaseTitleActivity {
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.tv_phone)
    TextView tvPhone;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.ll_address)
    LinearLayout llAddress;
    @BindView(R.id.tv_add_address)
    TextView tvAddAddress;
    @BindView(R.id.ll_select_address)
    LinearLayout llSelectAddress;
    @BindView(R.id.ll_goods)
    LinearLayout llGoods;

    @BindView(R.id.tv_money)
    TextView tvMoney;
    @BindView(R.id.tv_enter)
    TextView tvEnter;
    @BindView(R.id.edt_note)
    EditText edtNote;
    @BindView(R.id.tv_goods_price)
    TextView tvGoodsPrice;
    @BindView(R.id.tv_freight_price)
    TextView tvFreightPrice;
    @BindView(R.id.tv_all_price)
    TextView tvAllPrice;
    @BindView(R.id.tv_back_price)
    TextView tvBackPrice;

    private LayoutInflater mInflater;
    private CartListModel cartListModel;
    private List<CartListModel> cartListModels;
    private double money;
    private double freight;
    private AddressModel addressModel;


    public static void startActivity(Context context, CartListModel cartListModel, AddressModel addressModel) {
        Intent intent = new Intent(context, NewGoodsOrderActivity.class);
        intent.putExtra("cartListModel", cartListModel);
        intent.putExtra("address", addressModel);
        context.startActivity(intent);
    }

    public static void startActivity(Context context, List<CartListModel> list) {
        Intent intent = new Intent(context, NewGoodsOrderActivity.class);
        intent.putExtra("cartListModels", (Serializable) list);
        context.startActivity(intent);
    }


    @Override
    protected void initTopBar() {
        initBack();
        getTitleText().setText("确认订单");
    }

    @Override
    protected void initLayout() {
        setContentView(R.layout.activity_new_goods_order);
    }

    @Override
    protected void initView() {
        if (getIntent() != null) {
            if (getIntent().getSerializableExtra("cartListModel") != null)
                cartListModel = (CartListModel) getIntent().getSerializableExtra("cartListModel");
            if (getIntent().getSerializableExtra("cartListModels") != null)
                cartListModels = (List<CartListModel>) getIntent().getSerializableExtra("cartListModels");
            if (getIntent().getSerializableExtra("address") != null)
                addressModel = (AddressModel) getIntent().getSerializableExtra("addressModel");
        }
        if (cartListModel == null && (cartListModels == null || cartListModels.size() == 0))
            return;
        mInflater = LayoutInflater.from(this);

        View viewLine = null;

        int num = 0;
        double rebate_price = 0;
        if (cartListModel != null) {
            View view = mInflater.inflate(R.layout.layout_appraisal_goods_item, llGoods, false);
            ImageView ivImg = view.findViewById(R.id.iv_img);
            TextView tvTitle = view.findViewById(R.id.tv_title);
            TextView tvGoodsPrice = view.findViewById(R.id.tv_goods_price);
            TextView tvGoodsNum = view.findViewById(R.id.tv_goods_num);
            TextView tvValue = view.findViewById(R.id.tv_value);
            viewLine = view.findViewById(R.id.view_line);
            HCUtils.loadWebImg(this, ivImg, cartListModel.getImages());
            tvTitle.setText(cartListModel.getGoods_name());
            tvGoodsPrice.setText(PriceUtils.getPriceText2(cartListModel.getGoods_price()));
            tvGoodsNum.setText((String.valueOf(cartListModel.getBuy_num())));
            tvValue.setText(cartListModel.getSpec_value() == null ? "" : cartListModel.getSpec_value());
            llGoods.addView(view);
            money = money + PriceUtils.getMultiply(cartListModel.getBuy_num(), cartListModel.getGoods_price());
            num = cartListModel.getBuy_num();
            rebate_price = PriceUtils.getMultiply(num, cartListModel.getRebate_price());
        } else if (cartListModels != null) {
            for (CartListModel model : cartListModels) {
                View view = mInflater.inflate(R.layout.layout_appraisal_goods_item, llGoods, false);
                ImageView ivImg = (ImageView) view.findViewById(R.id.iv_img);
                TextView tvTitle = (TextView) view.findViewById(R.id.tv_title);
                TextView tvGoodsPrice = (TextView) view.findViewById(R.id.tv_goods_price);
                TextView tvGoodsNum = (TextView) view.findViewById(R.id.tv_goods_num);
                TextView tvValue = view.findViewById(R.id.tv_value);
                viewLine = view.findViewById(R.id.view_line);

                HCUtils.loadWebImg(this, ivImg, model.getImages());
                tvTitle.setText(model.getGoods_name());
                tvGoodsPrice.setText(PriceUtils.getPriceText2(model.getGoods_price()));
                tvGoodsNum.setText((String.valueOf(model.getBuy_num())));
                tvValue.setText(model.getSpec_value() == null ? "" : model.getSpec_value());
                llGoods.addView(view);
                money = money + PriceUtils.getMultiply(model.getBuy_num(), model.getGoods_price());
                num = num + model.getBuy_num();
                rebate_price = rebate_price + PriceUtils.getMultiply(model.getBuy_num(), model.getRebate_price());
            }
        }
        tvEnter.setText("结算 (" + num + ")");
        if (viewLine != null) viewLine.setVisibility(View.GONE);
        tvGoodsPrice.setText(PriceUtils.getPriceText2(money));
        tvAllPrice.setText(PriceUtils.getPriceText2(money));
        tvMoney.setText(PriceUtils.getPriceText2(money));
        tvBackPrice.setText(PriceUtils.getPriceText2(rebate_price));

        edtNote.clearFocus();

    }

    @Override
    protected void initDates() {
        setAddress();
        if (addressModel == null) {
            refreshAddress();
        }
    }

    @Override
    protected void initListener() {

    }


    @OnClick({R.id.ll_select_address, R.id.tv_enter})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_select_address: {
                Intent intent = new Intent(this, AddressActivity.class);
                intent.putExtra("isSelect", true);
                startActivityForResult(intent, 221);
            }
            break;
            case R.id.tv_enter:
                tvEnter.setEnabled(false);
                if (!enter())
                    tvEnter.setEnabled(true);
                break;
        }
    }

    private boolean enter() {
        if (addressModel == null) {
            toast("请选择收货地址");
            return false;
        }

        NewGoodsOrderModel model = new NewGoodsOrderModel();
        model.setAddress_id(addressModel.getAddress_id());
        if (!TextUtils.isEmpty(edtNote.getText()))
            model.setNote(edtNote.getText().toString());
        if (cartListModels == null) {
            model.setIs_cart(0);
            model.setCart_ids(null);
            model.setGoods_id(cartListModel.getGoods_id());
            model.setBuy_num(cartListModel.getBuy_num());
            model.setGoods_spec_id(cartListModel.getGoods_spec_id());
        } else {
            model.setIs_cart(1);
            String cart_ids = "";
            for (CartListModel cartListModel : cartListModels) {
                cart_ids = cart_ids + String.valueOf(cartListModel.getCart_id()) + ",";
            }
            if (cart_ids.length() > 1)
                cart_ids = cart_ids.substring(0, cart_ids.length() - 1);
            model.setCart_ids(cart_ids);
        }
        PayActivity.startActivity(this, model, money + freight);
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                if (requestCode == 221) {
                    addressModel = (AddressModel) data.getSerializableExtra("model");
                    setAddress();
                } else if (requestCode == 215) {
                    finish();
                }
            }
        }
    }


    private void setAddress() {

        if (addressModel == null) {
            llAddress.setVisibility(View.GONE);
            tvAddAddress.setVisibility(View.VISIBLE);
        } else {
            llAddress.setVisibility(View.VISIBLE);
            tvAddAddress.setVisibility(View.GONE);
            tvName.setText(addressModel.getName());
            tvPhone.setText(addressModel.getPhone());
            tvAddress.setText(addressModel.getLocation() + addressModel.getDetail());
            if (cartListModel != null) {
                getFreight(cartListModel.getGoods_id(), cartListModel.getBuy_num(), cartListModel.getGoods_spec_id(), 0, null);
            } else if (cartListModels != null && cartListModels.size() > 0) {
                String cart_ids = "";
                for (CartListModel model : cartListModels) {
                    cart_ids = cart_ids + model.getCart_id() + ",";
                }
                if (cart_ids.length() > 0) {
                    cart_ids = cart_ids.substring(0, cart_ids.length() - 1);
                }
                getFreight(0, 0, null, 1, cart_ids);
            }

        }


    }


    //加载默认地址
    private void refreshAddress() {
        new HttpRequest<AddressResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .setApiCode(ApiCst.getAddressList)
                .setListener(new HttpRequest.OnNetworkListener<AddressResponse>() {
                    @Override
                    public void onSuccess(AddressResponse response) {
                        List<AddressModel> list = response.getList();
                        if (list == null || list.size() == 0) return;
                        for (AddressModel addressModel : list) {
                            if (addressModel != null && addressModel.getIsdefault() == 1) {
                                NewGoodsOrderActivity.this.addressModel = addressModel;
                                setAddress();
                            }
                        }
                    }

                    @Override
                    public void onFail(String message, AddressResponse response) {
                        toast(message);
                        dissmissLoadingDialog();
                    }
                })
                .start(new AddressResponse());
    }


    @Override
    protected void onResume() {
        super.onResume();
        tvEnter.setEnabled(true);
    }


    private void getFreight(int goods_id, int goods_num, String goods_spec_id, int is_cart, String cart_ids) {
        new HttpRequest<DefaultResponse>()
                .with(this)
                .addParam("token", App.getToken(mContext))
                .addParam("address_id", addressModel.getAddress_id())
                .addParam("is_cart", is_cart)
                .addParam("cart_ids", cart_ids)
                .addParam("goods_id", goods_id)
                .addParam("goods_num", goods_num)
                .addParam("goods_spec_id", goods_spec_id)
                .setApiCode(ApiCst.getPostfee)
                .setListener(new HttpRequest.OnNetworkListener<DefaultResponse>() {
                    @Override
                    public void onSuccess(DefaultResponse response) {
                        JSONObject object = null;
                        try {
                            object = new JSONObject(response.content);
                            freight = object.optDouble("post_fee", 0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        tvFreightPrice.setText(PriceUtils.getPriceText2(freight));
                        String price = PriceUtils.getPriceText2(money + freight);
                        tvAllPrice.setText(price);
                        tvMoney.setText(price);
                    }

                    @Override
                    public void onFail(String message, DefaultResponse response) {
                        HCUtils.loadFail(mContext, message);
                    }
                })
                .start(new DefaultResponse());
    }


}
